<template>
  <div class="app-container">
    <el-card>
      <!--用户数据-->
      <el-form :model="queryParams" ref="queryForm" size="small" label-width="100px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="实践课程" prop="practiceType">
              <el-select v-model="queryParams.practiceType" placeholder="请选择" clearable style="width: 100%"
                @change="handleQuery">
                <el-option v-for="item in practiceTypeList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试卷名称">
              <el-input v-model.trim="queryParams.name" placeholder="输入内容" clearable @input="getList"
                @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="试卷状态" prop="taskStatus">
              <el-select v-model="queryParams.status" placeholder="请选择" clearable @change="handleQuery"
                style="width: 100%">
                <el-option v-for="item in statusList" :key="item.id" :label="item.type" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布时间">
              <el-date-picker v-model="dateRangeQuery" @change="handleQuery" value-format="yyyy-MM-dd" type="daterange"
                range-separator="-" style="width: 100%" start-placeholder="起始日期" end-placeholder="截至日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="所 属 学 期">
              <el-select v-model="queryParams.semesterConfigId" placeholder="请选择" clearable @change="handleQuery">
                <el-option v-for="item in querySemesterList" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-form-item>
              <!-- <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button> -->
              <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin-bottom: 10px;">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" v-hasPermi="['project:paper:generatePaper']"
          @click="addGroupBtn">新增组卷</el-button>
      </div>
      <el-table v-loading="loading" :data="tableList" @sort-change="sortChange">
        <el-table-column type="index" width="50" align="center" />
        <el-table-column label="试卷名称" align="center" prop="name" :show-overflow-tooltip="true" sortable="custom" />
        <el-table-column label="考试时间" align="center" width="180" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.startTime.slice(0, 10) }} ~ {{ scope.row.endTime.slice(0, 10) }}
          </template>
        </el-table-column>
        <el-table-column label="实践课程" align="center">
          <template slot-scope="scope">
            {{ (practiceTypeList.find(v => v.id == scope.row.practiceType) || {}).name }}
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center" prop="createTime" sortable="custom">
          <template slot-scope="scope">
            {{ (scope.row.releaseTime || '').slice(0, 16) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            {{ (statusList.find(v => v.id == scope.row.status) || {}).type }}
          </template>
        </el-table-column>
        <el-table-column label="创建人/发布人" align="center">
          <template slot-scope="scope">
            <!-- {{ scope.row.createUserName }} {{ scope.row.jsNumber ? '(' + scope.row.jsNumber + ')' : '' }} -->
            {{ scope.row.status != 0 ? scope.row.releaseByName : scope.row.createUserName }}({{ scope.row.status != 0 ?
              scope.row.releaseJsNumber : scope.row.jsNumber }})
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status === 0" type="text" @click="handleModifyStatus(scope.row.id, 'list')"
              v-hasPermi="['project:paper:publish']">
              发 布
            </el-button>
            <el-button type="text" v-else @click="previewBank(scope.row)">预 览</el-button>
            <el-button v-if="scope.row.status === 0" type="text" @click="editButton(scope.row)"
              v-hasPermi="['project:paper:edit']">
              编 辑
            </el-button>
            <el-button v-if="scope.row.status === 0" style="color: #f56c6c;" type="text" @click="handleDelete(scope.row)"
              v-hasPermi="['project:paper:remove']">
              删 除
            </el-button>
            <el-button type="text" v-if="scope.row.status != 0 && scope.row.status != 1"
              v-hasPermi="['project:paper:performanceXy']" @click="updateBank(scope.row)">完成情况</el-button>
            <el-button v-if="scope.row.status === 2 || scope.row.status == 1" style="color: #f56c6c;" type="text"
              @click="handleWithdraw(scope.row)" v-hasPermi="['project:paper:withdraw']">
              撤 回
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 试卷详情 -->
      <el-dialog title="试卷详情" width="60%" :visible.sync="open" append-to-body class="dialogClass xiangqing" center>
        <el-form ref="form" :model="form" label-suffix=":">
          <el-card style="margin-top: 5px;margin-bottom: 5px;">
            <el-row>
              <el-col :span="24">
                <el-form-item label="" style="margin: 0;">
                  <div class="inforClass">试题基本信息</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="试卷名称">
                  <el-tooltip class="item" effect="dark" :content="form.name" placement="top-start">
                    <div class="ellipsis-text">
                      {{ form.name }}
                    </div>
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="实践课程">
                  <div>{{ (practiceTypeList.find(v => v.id == form.practiceType) || {}).name }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="积分上限">
                  <div>{{ form.score }}</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="面向学院">
                  <el-tooltip class="item" effect="dark" :content="(form.faceXyNameList || []).join('、') || '全部'"
                    placement="top-start">
                    <div class="ellipsis-text">
                      {{ (form.faceXyNameList || []).join('、') || '全部' }}
                    </div>
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="面向专业">
                  <el-tooltip class="item" effect="dark" :content="(form.faceZyNameList || []).join('、') || '全部'"
                    placement="top-start">
                    <div class="ellipsis-text">
                      {{ (form.faceZyNameList || []).join('、') || '全部' }}
                    </div>
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="面向班级">
                  <el-tooltip class="item" effect="dark" :content="(form.faceBjNameList || []).join('、') || '全部'"
                    placement="top-start">
                    <div class="ellipsis-text">
                      {{ (form.faceBjNameList || []).join('、') || '全部' }}
                    </div>
                  </el-tooltip>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="面向年级">
                  <el-tooltip class="item" effect="dark" :content="form.faceNj || '全部'" placement="top-start">
                    <div class="ellipsis-text">
                      {{ form.faceNj || '全部' }}
                    </div>
                  </el-tooltip>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="发布时间">
                  <div>{{ (form.releaseTime || '').slice(0, 16) }}</div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="考试时间">
                  <div>{{ (form.startTime || '').slice(0, 10) }} ~ {{ (form.endTime || '').slice(0, 10) }}</div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
        <el-row>
          <el-card style="margin-top: 5px;margin-bottom: 5px;">
            <el-col :span="24">
              <div class="inforClass">题目详情</div>
            </el-col>
            <el-col :span="24" v-for="(item, index) in topicList" :key="index">
              <div style="display: flex; font-weight: 600;align-items: center;">
                <div>{{ index + 1 }}.</div>
                <div style="margin: 0 8px;">[{{ item.type == 1 ? '单选题' : item.type == 2 ? '判断题' : '多选题' }}]</div>
                <div v-html="item.questionContent"></div>
                <div> ({{ item.type == 1 ? form.selectScore : item.type == 2 ? form.judgeScore :
                  form.multipleScore }} 分)</div>
              </div>
              <div v-for="it in item.questionBankOptionList" :key="it.name" class="bankLabelStyle">
                <el-checkbox v-model="it.answer" :label="it.name" style="display: block;"
                  class="non-clickable-checkbox" />
                <span> {{ item.name }}. </span>
                <div style="flex: 1" v-html="it.content"></div>
              </div>
              <div>
                <el-form>
                  <el-form-item label="答案解析:">
                    <div v-html="item.answerAnalysis || '暂无解析'"></div>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-card>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="open = false">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 编辑 -->
      <el-dialog title="编辑试卷" width="55%" :visible.sync="editShow" append-to-body class="dialogClass" center>
        <el-form ref="editForm" :model="editForm" :rules="rules" label-width="110px" label-suffix=":">
          <el-card margin="0">
            <el-row>
              <el-col :span="24">
                <div class="inforClass">基础信息</div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="实践课程" prop="practiceType">
                  <el-select v-model="editForm.practiceType" placeholder="请选择实践课程" style="width:100%" disabled>
                    <el-option v-for="item in practiceTypeList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="试卷名称" prop="name">
                  <el-input v-model="editForm.name" placeholder="请输入试卷名称" maxlength="30" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="考试时间" prop="dateRangeQuery">
                  <el-date-picker v-model="editForm.dateRangeQuery" value-format="yyyy-MM-dd" type="daterange"
                    range-separator="-" style="width: 100%" start-placeholder="开始日期" end-placeholder="结束日期"
                    @input="$forceUpdate()" @change="getSemes"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="所属学期">
                  <el-select v-model="editForm.semesterConfigId" placeholder="请选择考试时间" style="width:100%">
                    <el-option v-for="item in semesterList" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="答题时长" prop="allTime">
                  <el-input-number size="mini" v-model="editForm.allTime" :min="0" />分钟
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <div class="inforClass">面向对象</div>
              </el-col>
              <el-col :span="12">
                <el-form-item label="面向学院" prop="faceXy">
                  <el-select v-model="editForm.faceXy" clearable @change="handlelistProxy" multiple collapse-tags>
                    <el-option v-for="item in proxyEditList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="面向专业" prop="faceZy">
                  <el-select v-model="editForm.faceZy" clearable @change="handlelistProzy" multiple collapse-tags>
                    <el-option v-for="item in prozyEditList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="面向年级" prop="faceNj">
                  <el-select v-model="editForm.faceNj" clearable @change="handlelistProNj" multiple collapse-tags>
                    <el-option v-for="item in pronjEditList" :key="item.id" :label="item.name" :value="item.name" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="面向班级" prop="faceBj">
                  <el-select v-model="editForm.faceBj" clearable @change="handlelistProbj" multiple collapse-tags>
                    <el-option v-for="item in probjEditList" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
        <el-row>
          <el-card style="margin-top: 5px;margin-bottom: 5px;">
            <el-col :span="24">
              <div class="inforClass">题目详情</div>
            </el-col>
            <el-col :span="24" v-for="(item, index) in topicList" :key="index">
              <div style="display: flex; font-weight: 600;align-items: center;">
                <div>{{ index + 1 }}.</div>
                <div style="margin: 0 8px;">[{{ item.type == 1 ? '单选题' : item.type == 2 ? '判断题' : '多选题' }}]</div>
                <div v-html="item.questionContent"></div>
                <div> ({{ item.type == 1 ? form.selectScore : item.type == 2 ? form.judgeScore :
                  form.multipleScore }} 分)</div>
              </div>
              <div v-for="it in item.questionBankOptionList" :key="it.name" class="bankLabelStyle">
                <el-checkbox v-model="it.answer" :label="it.name" style="display: block;"
                  class="non-clickable-checkbox" />
                <span> {{ item.name }}. </span>
                <div style="flex: 1" v-html="it.content"></div>
              </div>
              <div>
                <el-form>
                  <el-form-item label="答案解析:">
                    <div v-html="item.answerAnalysis || '暂无解析'"></div>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-card>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" @click="handleDelete(editForm)" v-hasPermi="['project:paper:remove']">删 除</el-button>
          <el-button @click="editSave">保 存</el-button>
          <el-button type="primary" @click="handleModifyStatus(editForm, 'edit')" v-hasPermi="['project:paper:publish']">发
            布</el-button>
        </div>
      </el-dialog>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>
  </div>
</template>

<script>
import { typeCongfigList } from "@/api/semesManage";
import { projectList } from "@/api/semesManage";
import { paperList, modifyStatus, getTestInfo, modifyDelete } from "@/api/paperInterlocu/paper";
import { listProxy, listProzy, listProbj, pronjList } from "@/api/project/prold";
export default {
  name: "publishedManage",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      tableList: [],
      proxyList: [], // 学院
      prozyList: [], // 专业
      probjList: [], // 班级
      pronjList: [], // 年级
      practiceTypeList: [], // 实践课程
      statusList: [{ id: 0, type: '未发布' }, { id: 1, type: '未开始' }, { id: 2, type: '进行中' }, { id: 3, type: '已结束' }],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined,
        practiceType: undefined,
        createTimeSort: 'desc'
      },
      dateRangeQuery: [],
      open: false,
      topicList: [],
      form: {},
      editShow: false,
      editForm: {},
      proxyEditList: [],
      prozyEditList: [], //
      probjEditList: [],
      pronjEditList: [],

      rules: {
        practiceType: [
          { required: true, message: "请选择实践课程" },
        ],
        name: [
          { required: true, message: "试卷名称不得为空", trigger: "blur" },
        ],
        faceXy: [
          { type: 'array', required: true, message: "请选择学院" },
        ],
        faceZy: [
          { type: 'array', required: true, message: "请选择专业" },
        ],
        faceBj: [
          { type: 'array', required: true, message: "请选择班级" },
        ],
        faceNj: [
          { type: 'array', required: true, message: "请选择年级" },
        ],
        allTime: [
          { required: true, message: "请设置答题时长", trigger: "blur" },
          { validator: this.checkAllTime, trigger: 'blur' }
        ],
        dateRangeQuery: [
          { type: 'array', required: true, message: "请选择考试时间段", trigger: "change" },
        ],
      },
      semesterList: [],
      querySemesterList: [],
    };
  },
  watch: {},
  created() {
    // const permissList = sessionStorage.getItem('practiceTypes').split(',');
    // const typeMap = {
    //   1: { type: '劳动教育', id: 1 },
    //   2: { type: '职业素养', id: 2 },
    //   3: { type: '应急安全', id: 3 },
    //   4: { type: '思政实践', id: 4 },
    //   5: { type: '创新创业', id: 5 }
    // };

    // permissList.forEach(v => {
    //   if (typeMap[v]) {
    //     this.practiceTypeList.push(typeMap[v]);
    //   }
    // });
    this.getTypeCongfigList();
    this.querySemester();
    this.getListProxy();
    this.getListProzy();
    this.getListProbj();
    this.getListPronj();
    this.getList();
  },
  methods: {
    querySemester() {
      projectList().then((res) => {
        if (res.code == 200) {
          this.querySemesterList = res.rows;
        }
      });
    },
    getTypeCongfigList() {
      typeCongfigList({
        pageNum: 1,
        pageSize: 50,
      }).then(res => {
        this.practiceTypeList = res.rows;
      });
    },
    getSemes(e) {
      this.semesterList = [];
      if (e) {
        projectList({
          startTime: e[0] + ' 00:00:00',
        }).then((res) => {
          if (res.code == 200) {
            this.semesterList = res.rows.filter(item => {
              if (
                (new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() <= new Date(item.endTime).getTime())
                ||
                (new Date(e[0] + ' 00:00:00').getTime() <= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() <= new Date(item.endTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.startTime).getTime())
                ||
                (new Date(e[0] + ' 00:00:00').getTime() >= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.endTime).getTime())
              ) {
                return item;
              }
            });
            this.editForm.semesterConfigId = this.semesterList.length > 0 ? this.semesterList[0].id : null;
          }
        });
      } else {
        this.editForm.semesterConfigId = null;
      }
    },
    // 自定义校验方法
    checkAllTime(rule, value, callback) {
      if (value === 0) {
        callback(new Error('答题时长不能为0'));
      } else {
        callback();
      }
    },
    getList() {
      const time = this.dateRangeQuery && this.dateRangeQuery.length > 0 ? { startTime: this.dateRangeQuery[0] + ' 00:00:00', endTime: this.dateRangeQuery[1] + ' 23:59:59' } : {};
      paperList({ ...this.queryParams, ...time }).then(res => {
        if (res.code === 200) {
          this.tableList = res.rows;
          this.tableList.forEach((item) => {
            // 学院
            if (item.faceXy) {
              item.faceXyId = item.faceXy.split(',');
              item.faceXyNameList = [];
              this.proxyList.forEach(v => {
                item.faceXyId.forEach(y => {
                  if (y == v.id) {
                    item.faceXyNameList.push(v.name);
                  }
                })
              })
            } else {
              item.faceXyNameList = ['全部'];
            }
            // 专业
            if (item.faceZy) {
              item.faceZyId = item.faceZy.split(',');
              item.faceZyNameList = [];
              this.prozyList.forEach(v => {
                item.faceZyId.forEach(y => {
                  if (y == v.id) {
                    item.faceZyNameList.push(v.name);
                  }
                })
              })
            } else {
              item.faceZyNameList = ['全部'];
            }
            // 班级
            if (item.faceBj) {
              item.faceBjId = item.faceBj.split(',');
              item.faceBjNameList = [];
              this.probjList.forEach(v => {
                item.faceBjId.forEach(y => {
                  if (y == v.id) {
                    item.faceBjNameList.push(v.name);
                  }
                })
              })
            } else {
              item.faceBjNameList = ['全部'];
            }
          });
          this.total = res.total;
        }
      })
    },
    sortChange(row) {
      const sortMap = {
        name: 'testPaperNameSort',
        createTime: 'createTimeSort',
      };

      // 提取排序方向的函数
      const getSortOrder = (order) => {
        if (order === 'ascending') return 'asc';
        if (order === 'descending') return 'desc';
        return null;  // 如果不是 'ascending' 或 'descending'，返回 null
      };

      // 获取对应的排序字段和排序方向
      const sortField = sortMap[row.prop];
      const sortOrder = getSortOrder(row.order);

      // 如果找到对应的排序字段，则调用 getList
      if (sortField) {
        this.queryParams.pageNum = 1;
        this.queryParams.pageSize = 10;

        const oldSortFields = ["testPaperNameSort", "createTimeSort"];
        oldSortFields.forEach((field) => {
          if (this.queryParams[field]) {
            delete this.queryParams[field];
          }
        });

        this.queryParams[sortField] = sortOrder;
        // this.getList({ [sortField]: sortOrder });
        this.getList();
      }
    },
    // 查询学院
    getListProxy() {
      listProxy().then((response) => {
        response.rows.forEach(v => {
          this.proxyList.push(v);
          this.proxyEditList.push(v);
        });
        if (response.rows.length > 0) {
          this.proxyEditList.unshift({ name: '全部', id: '999999' });
        };
      });
    },
    // 查询专业
    getListProzy() {
      listProzy().then((response) => {
        this.prozyList = response.rows;
      });
    },
    // 查询班级
    getListProbj() {
      listProbj().then((response) => {
        this.probjList = response.rows;
      });
    },
    // 查询年级
    getListPronj() {
      pronjList().then((response) => {
        response.rows.forEach(v => {
          this.pronjList.push(v);
          this.pronjEditList.push(v);
        });
        if (response.rows.length > 0) {
          this.pronjEditList.unshift({ name: '全部', id: '999999999999' });
        };

      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeQuery = [];
      this.queryParams = {
        name: undefined,
        status: undefined,
        practiceType: undefined,
        createTimeSort: 'desc'
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    previewBank(row) {
      this.open = true;
      this.form = { ...row };
      this.queryTestInfo(row.id);
    },
    // 新增
    addGroupBtn() {
      this.$router.push({ path: "/addGroup" })
    },
    updateBank(row) {
      const data = {
        id: row.id,
        type: row.practiceType,
        score: row.score,
        name: row.name,
        judgeScore: row.judgeScore,
        multipleScore: row.multipleScore,
        selectScore: row.selectScore,
        time: row.startTime.slice(0, 10) + '~' + row.endTime.slice(0, 10),
        xyIdList: row.faceXy,
        zyIdList: row.faceZy,
        bjIdList: row.faceBj
      };
      this.$router.push({ path: '/markingView', query: { ...data } },);
    },
    handleModifyStatus(row, type) {
      let query = {};
      if (type == 'edit') {
        let data = { ...row };
        if (!this.editForm.dateRangeQuery || this.editForm.dateRangeQuery.length === 0) return this.$modal.msgError("请选择时间");
        if (!this.editForm.allTime || this.editForm.allTime == 0) return this.$modal.msgError("答题时长不得为空或不得为0!");
        if (!this.editForm.faceXy || this.editForm.faceXy.length == 0) return this.$modal.msgError("请选择面向学院!");
        if (!this.editForm.faceZy || this.editForm.faceZy.length == 0) return this.$modal.msgError("请选择面向专业!");
        if (!this.editForm.faceNj || this.editForm.faceNj.length == 0) return this.$modal.msgError("请选择面向年级!");
        if (!this.editForm.faceBj || this.editForm.faceBj.length == 0) return this.$modal.msgError("请选择面向班级!");
        data.startTime = this.editForm.dateRangeQuery[0] + ' 00:00:00';
        data.endTime = this.editForm.dateRangeQuery[1] + ' 23:59:59';
        const faceObj = this.validateForm();
        query = { ...data, ...faceObj, status: 1 }
      } else {
        query = { id: row, status: 1 }
      }
      modifyStatus(query).then(res => {
        if (res.code == 200) {
          this.$modal.msgSuccess("发布成功");
          this.clearEdit();
        }
      })
    },
    editSave() {
      let data = { ...this.editForm };
      if (!this.editForm.dateRangeQuery || this.editForm.dateRangeQuery.length === 0) return this.$modal.msgError("请选择时间");
      if (!this.editForm.allTime || this.editForm.allTime == 0) return this.$modal.msgError("答题时长不得为空或不得为0!");
      if (!this.editForm.faceXy || this.editForm.faceXy.length == 0) return this.$modal.msgError("请选择面向学院!");
      if (!this.editForm.faceZy || this.editForm.faceZy.length == 0) return this.$modal.msgError("请选择面向专业!");
      if (!this.editForm.faceNj || this.editForm.faceNj.length == 0) return this.$modal.msgError("请选择面向年级!");
      if (!this.editForm.faceBj || this.editForm.faceBj.length == 0) return this.$modal.msgError("请选择面向班级!");
      data.startTime = this.editForm.dateRangeQuery[0] + ' 00:00:00';
      data.endTime = this.editForm.dateRangeQuery[1] + ' 23:59:59';
      const faceObj = this.validateForm();
      modifyStatus({ ...data, ...faceObj }).then(res => {
        if (res.code == 200) {
          this.$modal.msgSuccess("编辑成功");
          this.clearEdit();
        }
      })
    },
    validateForm() {
      let faceObj = {
        faceXy: this.editForm.faceXy && this.editForm.faceXy.find(v => v == '999999') ? [] : this.editForm.faceXy,
        faceZy: this.editForm.faceZy && this.editForm.faceZy.find(v => v == '99999999') ? [] : this.editForm.faceZy,
        faceNj: this.editForm.faceNj && this.editForm.faceNj.find(v => v == '全部') ? [] : this.editForm.faceNj,
        faceBj: this.editForm.faceBj && this.editForm.faceBj.find(v => v == '9999999999') ? [] : this.editForm.faceBj,
      };
      // 如果没有任何值，使用 proxyEditList 和其它相关列表的映射值
      if (!faceObj.faceXy && !faceObj.faceZy && !faceObj.faceNj && !faceObj.faceBj) {
        faceObj.faceXy = this.proxyEditList.map(v => v.id).join(',');
        faceObj.faceZy = this.prozyEditList.map(v => v.id).join(',');
        faceObj.faceNj = this.pronjEditList.map(v => v.name).join(',');
        faceObj.faceBj = this.probjEditList.map(v => v.id).join(',');
      } else {
        // 否则，根据每个字段是否存在决定是否 join
        if (faceObj.faceXy.length > 0) {
          faceObj.faceXy = Array.isArray(faceObj.faceXy) ? faceObj.faceXy.join(',') : faceObj.faceXy;
        } else {
          faceObj.faceXy = this.proxyEditList.slice(1).map(v => v.id).join(',');
        }
        if (faceObj.faceZy.length > 0) {
          faceObj.faceZy = Array.isArray(faceObj.faceZy) ? faceObj.faceZy.join(',') : faceObj.faceZy;
        } else {
          faceObj.faceZy = this.prozyEditList.slice(1).map(v => v.id).join(',');
        }
        if (faceObj.faceNj.length > 0) {
          faceObj.faceNj = Array.isArray(faceObj.faceNj) ? faceObj.faceNj.join(',') : faceObj.faceNj;
        } else {
          faceObj.faceNj = this.pronjEditList.slice(1).map(v => v.name).join(',');
        }
        if (faceObj.faceBj.length > 0) {
          faceObj.faceBj = Array.isArray(faceObj.faceBj) ? faceObj.faceBj.join(',') : faceObj.faceBj;
        } else {
          faceObj.faceBj = this.probjEditList.slice(1).map(v => v.id).join(',');
        }
      }

      return faceObj;
    },
    // 清除
    clearEdit() {
      this.getList();
      this.editShow = false;
      this.editForm = {};
      this.form = {};
    },
    // 编辑
    editButton(row) {
      this.editShow = true;
      this.resetForm("editForm");
      this.editForm = JSON.parse(JSON.stringify(row));
      this.$set(this.editForm, 'dateRangeQuery', [this.editForm.startTime.slice(0, 10), this.editForm.endTime.slice(0, 10)]);
      this.getSemes([this.editForm.startTime.slice(0, 10), this.editForm.endTime.slice(0, 10)]);
      // 学院
      if (row.faceXy) {
        this.editForm.faceXy = row.faceXy.split(',');
      }
      // 专业
      if (row.faceZy) {
        this.editForm.faceZy = row.faceZy.split(',');
        this.getEditProzy(this.editForm.faceXy);
      }
      // 年级
      if (row.faceNj) {
        this.editForm.faceNj = row.faceNj.split(',');
      }
      // 班级
      if (row.faceBj) {
        this.editForm.faceBj = row.faceBj.split(',');
        this.getEditProbj(this.editForm.faceZy);
      }
      this.queryTestInfo(row.id);
    },

    // 切换学院
    handlelistProxy(id) {
      this.prozyEditList = [];
      this.probjEditList = [];
      if (!id) {
        this.editForm.faceXy = null;
      };
      if (id.length > 0) {
        if (id.length > 1 && id.find(x => x === '999999')) {
          if (this.editForm.faceXy.find(x => x === '999999') && id[0] == '999999') {
            this.editForm.faceXy.splice(this.editForm.faceXy.findIndex(x => x === '999999'), 1);
          }
          if (id.find(x => x === '999999') && id[0] !== '999999') {
            this.editForm.faceXy = ['999999'];
          }
        }
        if (this.proxyEditList.length > 0 && this.proxyEditList[0].id === '999999' && this.proxyEditList.length - 1 == id.length) {
          this.editForm.faceXy = ['999999'];
        }
      }
      if (this.editForm.faceXy && this.editForm.faceXy.length > 0) {
        this.getEditProzy(this.editForm.faceXy);
      }

      this.editForm.faceZy = null;
      this.editForm.faceBj = null
    },
    // 切换专业
    handlelistProzy(id) {
      this.probjEditList = [];
      if (!id) {
        this.editForm.faceZy = null;
      };
      if (id.length > 0) {
        if (id.length > 1 && id.find(x => x === '99999999')) {
          if (this.editForm.faceZy.findIndex(x => x === '99999999') >= 0 && id[0] == '99999999') {
            this.editForm.faceZy.splice(this.editForm.faceZy.findIndex(x => x === '99999999'), 1);
          }
          if (id.find(x => x === '99999999') && id[0] !== '99999999') {
            this.editForm.faceZy = ['99999999'];
          }
        }
        if (this.prozyEditList.length > 0 && this.prozyEditList[0].id === '99999999' && this.prozyEditList.length - 1 == id.length) {
          this.editForm.faceZy = ['99999999'];
        }
        this.getEditProbj(this.editForm.faceZy);
      }
      this.editForm.faceBj = null;
    },
    // 切换班级
    handlelistProbj(id) {
      if (id.length > 0) {
        if (id.length > 1 && id.find(x => x === '9999999999')) {
          if (this.editForm.faceBj.findIndex(x => x === '9999999999') >= 0 && id[0] == '9999999999') {
            this.editForm.faceBj.splice(this.editForm.faceBj.findIndex(x => x === '9999999999'), 1);
          }
          if (id.find(x => x === '9999999999') && id[0] !== '9999999999') {
            this.editForm.faceBj = ['9999999999'];
          }
        }
        if (this.probjEditList.length > 0 && this.probjEditList[0].id === '9999999999' && this.probjEditList.length - 1 == id.length) {
          this.editForm.faceBj = ['9999999999'];
        }
      }
      this.$forceUpdate();
    },
    handlelistProNj(id) {
      this.probjEditList = [];
      if (!id) {
        this.editForm.faceNj = null;
      };
      if (id.length > 0) {
        if (id.length > 1 && id.find(x => x === '全部')) {
          if (this.editForm.faceNj.findIndex(x => x === '全部') >= 0 >= 0 && id[0] == '全部') {
            this.editForm.faceNj.splice(this.editForm.faceNj.findIndex(x => x === '全部'), 1);
          }
          if (id.find(x => x === '全部') && id[0] !== '全部') {
            this.editForm.faceNj = ['全部'];
          }
        }
        if (this.pronjEditList.length > 0 && this.pronjEditList[0].name === '全部' && this.pronjEditList.length - 1 == id.length) {
          this.editForm.faceNj = ['全部'];
        }
        if (this.prozyEditList.length > 0) {
          this.editForm.faceBj = null;
          this.getEditProbj(this.editForm.faceZy);
        }
      }
    },

    // 查询专业
    getEditProzy(id) {
      let data = {
        xyIds: [],
      };
      if (id) {
        if (id.includes('999999')) {
          data.xyIds = this.proxyEditList.map(xyId => xyId.id);
          data.xyIds = data.xyIds.filter(x => x !== '999999');
        } else {
          data.xyIds = id;
        }
      } else {
        data = {};
      }
      listProzy(data).then(async (response) => {
        this.prozyEditList = [];
        this.prozyEditList = response.rows;
        if (response.rows.length > 0) {
          this.prozyEditList.unshift({ name: '全部', id: '99999999' });
          await this.getEditProbj(['99999999']);
        };

      });
    },

    // 查询班级
    getEditProbj(id) {
      let data = {
        zyIds: [],
        njIds: this.editForm.faceNj[0] == '全部' ? this.pronjEditList.slice(1).map(v => v.name) : this.editForm.faceNj,
      };
      if (id) {
        data.zyIds = [];
        if (id.includes('99999999')) {
          data.zyIds = this.prozyEditList.map(xyId => xyId.id).filter(x => x !== '99999999');
        } else {
          data.zyIds = id;
        }
      }
      listProbj(data).then((response) => {
        this.probjEditList = [];
        this.probjEditList = response.rows;
        if (response.rows.length > 0) {
          this.probjEditList.unshift({ name: '全部', id: '9999999999' });
        };
      });
    },
    queryTestInfo(id) {
      getTestInfo({ id }).then(res => {
        this.topicList = res.data;
        res.data.forEach(item => {
          item.questionBankOptionList.forEach(it => {
            it.answer = it.answer == 1 ? true : false;
          });
        })
      })
    },
    handleWithdraw(row) {
      this.$modal
        .confirm('是否确认撤回"' + row.name + '"试卷名称的数据项？')
        .then(function () {
          return modifyStatus({ status: 0, id: row.id });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("撤回成功");
        })
        .catch(() => {
          // this.$modal.msgSuccess("撤回失败");
        });
    },
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除"' + row.name + '"试卷名称的数据项？')
        .then(function () {
          return modifyDelete(row.id);
        })
        .then(() => {
          this.getList();
          this.editShow = false;
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>
<style scoped lang="scss">
.bankLabelStyle {
  display: flex;
  min-height: 40px;
  align-items: center;
  margin-left: 20px;
}

::v-deep .el-form-item__content {
  p {
    margin: 0 !important;
  }
}

.ellipsis-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 设置复选框选中时的样式 */
.non-clickable-checkbox.el-checkbox--is-checked .el-checkbox__input {
  border-color: #409EFF;
  /* 选中时的边框颜色 */
  background-color: #409EFF;
  /* 选中时的背景颜色 */
}

/* 禁止点击，但保持选中样式 */
.non-clickable-checkbox {
  pointer-events: none;
}

/* 保持复选框已选中时的样式不变 */
.non-clickable-checkbox .el-checkbox__input.is-checked {
  background-color: #409EFF;
  /* 选中时背景色 */
  border-color: #409EFF;
  /* 选中时边框色 */
  color: white;
  /* 选中时文字颜色 */
}

/* 使复选框状态保持选中样式 */
.non-clickable-checkbox.el-checkbox--is-checked .el-checkbox__inner {
  background-color: #409EFF !important;
  /* 确保选中时的背景色 */
  border-color: #409EFF !important;
}

/* 保持选中复选框时不改变外观 */
.non-clickable-checkbox.is-checked .el-checkbox__input {
  background-color: #409EFF;
  border-color: #409EFF;
}

.dialogClass {
  ::v-deep .el-dialog__title {
    font-weight: 800;
  }

  ::v-deep .el-dialog__body {
    padding-top: 0 !important;
  }

  .xiangqing {

    ::v-deep .el-form-item {
      margin-bottom: 10px !important;

      .el-input {
        width: 80% !important;
      }

      label {
        font-weight: 550 !important;
        color: #000 !important;
      }
    }
  }

  .inforClass {
    font-size: 16px;
    font-weight: 700;
    display: flex;
    align-items: center;
  }

  .inforClass::before {
    content: '';
    width: 5px;
    height: 25px;
    background-color: #419eff;
    margin-right: 10px;
    display: inline-block;
  }
}

::v-deep .el-form-item__content {
  p {
    margin: 0 !important;
  }
}

::v-deep .el-input-number--mini {
  width: 100px !important;
}

::v-deep .el-input__inner {
  width: 100% !important;
  padding-left: 5px !important;
  padding-right: 5px !important;
}

::v-deep .el-input-number__decrease {
  display: none !important;
}

::v-deep .el-input--suffix {
  width: 100% !important;
}

::v-deep .el-select {
  width: 100% !important;
}

::v-deep .el-input-number__increase {
  display: none !important;
}
</style>
